﻿using System;
using System.Reflection;
using System.Collections.Generic;

namespace SBPweb.Forge.Communication.WCF
{

    public class MessageReceiveEventArgs<T> : MessageReceiveEventArgs
    {

        internal MessageReceiveEventArgs(T content)
            : base(content)
        {
        }

        public new T Message
        {
            get
            {
                return (T)base.Message;
            }
            set
            {
                base.Message = value;
            }
        }

    }

    public class MessageReceiveEventArgs : EventArgs
    {

        private static Dictionary<Type, ConstructorInfo> dict = new Dictionary<Type, ConstructorInfo>();

        internal MessageReceiveEventArgs(object message)
        {
            this.Message = message;
        }

        public object Message
        {
            get;
            set;
        }

        public object Command
        {
            get;
            internal set;
        }

        public static MessageReceiveEventArgs CreateGenericInstance(Type genericParameterType, object content)
        {
            Type t = Type.GetType(string.Format("{0}`1", typeof(MessageReceiveEventArgs).FullName));
            Type gT = t.MakeGenericType(new Type[] { genericParameterType });
            ConstructorInfo cI = GetConstructor(gT);
            return (MessageReceiveEventArgs)cI.Invoke(new object[] { content });
        }

        public static ConstructorInfo GetConstructor(Type type)
        {
            if (dict.ContainsKey(type))
            {
                return dict[type];
            }
            ConstructorInfo ret = type.GetConstructors(BindingFlags.CreateInstance | BindingFlags.Default | BindingFlags.NonPublic | BindingFlags.Instance)[0];
            return dict[type] = ret;
        }

    }
    
}
